package com.web.util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class JDBCUtil {
    public static int update(String sql,Object... args) {
        //连接词获得连接
        try (Connection connection= DataSourceUtils.getConnection();){
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            //设置参数
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            //执行命令
            int rows = preparedStatement.executeUpdate();
            return rows;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
    public static <T>List<T> query(Class<T> clazz,String sql,Object... args) {
        try(Connection connection = DataSourceUtils.getConnection()){
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i+1,args[i]);
            }
            List<T> list = new ArrayList<>();
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                T t = clazz.newInstance();
                Field[] fields = clazz.getDeclaredFields();
                for (Field field : fields) {
                    Object value = resultSet.getObject(field.getName());
                    field.setAccessible(true);
                    field.set(t,value);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
